package com.efounder.chat.item;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.utils.DateUtils;
import com.efounder.frame.ViewSize;
import com.efounder.message.struct.IMStruct002;
import com.efounder.ui.util.DisplayUtil;
import com.efounder.util.AbFragmentManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.math.BigDecimal;
import java.util.Hashtable;
import java.util.Map;

/**
 * 任务中心消息item
 * Created by kongmeng on 2018/12/27.
 * <p>
 * json:
 * "image": "http://panserver.solarsource.cn:9692/panserver/files/7e58f86f-646e-4206-84bc-3c6d6d62a052/download",
 * "AndroidShow": "com.efounder.taskcomps.activity.ApproveDetailsActivity",
 * "opType": "pending",
 * "show": "TaskDetailFCViewController",
 * "OP_TYPE": "pending",
 * "title": "通用申请流程",
 * "viewColumn": "[{\"id\":\"FLOW_NAME\",\"name\":\"单据类型\",\"type\":\"string\",\"color\":\"#000\"},{\"id\":\"BIZ_DJBH\",\"name\":\"单据编号\",\"type\":\"string\",\"color\":\"#000\"},{\"id\":\"OP_TIME\",\"name\":\"提交时间\",\"type\":\"datetime\",\"color\":\"#000\"}]",
 * "subtitleColor": "#000",
 * "systemName": "任务中心",
 * "subtitle": "新的待办",
 * "viewType": "display",
 * "smallIcon": "http://panserver.solarsource.cn:9692/panserver/files/7e58f86f-646e-4206-84bc-3c6d6d62a052/download",
 * "time": "2018-12-27 14:19:45",
 * "status": "normal"
 * changeMessage
 */

public class GXTaskMessageItem extends LinearLayout implements IMessageItem {

    private TextView tvState;
    private TextView tvTitle;
    private TextView tvSubTitle;
    private TextView tvId;
    private TextView tvTime;
    private ImageView ivStateBlue;
    private ImageView ivStateRed;
    private LinearLayout llContent;
    private LinearLayout llTitle;
    private LinearLayout llMessage;
    private RelativeLayout rlBottom;

    private IMStruct002 message;
    private Context mContext;
    private org.json.JSONObject mJSONObject;
    private AbFragmentManager mAbFragmentManager;

    public GXTaskMessageItem(Context context) {
        super(context);
        this.mContext = context;
        mAbFragmentManager = new AbFragmentManager(context);
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflate.inflate(R.layout.chat_item_gxtask, this);//注意第二个参数

        tvState = (TextView) findViewById(R.id.tv_gxtask_state);
        tvTitle = (TextView) findViewById(R.id.tv_task_title);
        tvSubTitle = (TextView) findViewById(R.id.tv_task_subTitle);
        tvId = (TextView) findViewById(R.id.tv_gxtask_id);
        tvTime = (TextView) findViewById(R.id.tv_gxtask_time);
        ivStateBlue = (ImageView) findViewById(R.id.iv_gxtask_flag);
        ivStateRed = (ImageView) findViewById(R.id.iv_gxtask_flag_false);
        llContent = (LinearLayout) findViewById(R.id.ll_task_content);
        llMessage = (LinearLayout) findViewById(R.id.ll_message);
        llTitle = (LinearLayout) findViewById(R.id.ll_title);
        rlBottom = (RelativeLayout) findViewById(R.id.rl_bottom);

        //先隐藏掉两个图标
        ivStateBlue.setVisibility(GONE);
        ivStateRed.setVisibility(GONE);

        //宽度
//        int width = DisplayUtil.getMobileWidth(context) * 2 / 3 - 20;
        int width = DisplayUtil.getMobileWidth(context) * 4 / 5;

        LayoutParams lp = new LayoutParams(width, LayoutParams.MATCH_PARENT);
        this.setLayoutParams(lp);
        this.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String json = null;
                boolean isActivity = false;
                try {
                    json = new String(message.getBody(), "UTF-8");
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json);
                    Map<String, Object> map = jsonObject;

                    //默认的进入activity或者fragment的动画
                    int inTransition = R.anim.slide_in_from_right;
                    int outTransition = R.anim.slide_out_to_left;
                    if (jsonObject.has("tcms")) {
                        String tcms = jsonObject.getString("tcms");
                        if (!tcms.equals("") && tcms.equals("present")) {
                            //由下向上弹出
                            inTransition = R.anim.push_bottom_in;
                            outTransition = R.anim.push_top_out;
                        } else if (!tcms.equals("") && tcms.equals("alert")) {

                        }
                    }

                    StubObject stubObject = new StubObject();
                    Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
                    stubObject.setStubTable(hashtable);
                    // Bundle bundle = new Bundle();
                    for (String key : map.keySet()) {
                        hashtable.put(key, map.get(key).toString());
                    }
                    //String AndroidShow =map.get("AndroidShow");//com.efounder.RNTaskDetailActivity"

                    hashtable.put("imStruct002", message);
                    if (jsonObject.has("AndroidShow")) {
                        String showClass = jsonObject.getString("AndroidShow");
                        if (jsonObject.optString("enableClick", "1").equals("0")) {//任务中心解决有些流程禁止访问详情
                            return;
                        }
                        //跳转前不进行资源文件判断
//                        if (showClass.equals("com.efounder.taskcomps.activity.ApproveDetailsActivity")) {
//                            //如果没有配置相应的类型，则弹框不跳转activity
//                            FormatSet formatSet = MobileFormatUtil.getInstance().getFormatSet();
//                            String djID = "";
//                            net.sf.json.JSONObject taskData = jsonObject.getJSONObject("TaskData");
//                            if (null != taskData) {
//                                String PFLOW_ID = taskData.optString("PFLOW_ID");
//                                if (PFLOW_ID != null && !PFLOW_ID.equals("")) {
//                                    djID = PFLOW_ID;
//                                } else {
//                                    djID = taskData.optString("FLOW_ID");
//                                }
//                            }
//                            if (null != djID && !djID.equals("")) {
//                                FormatTable hfmt = formatSet.getFormatTableById(djID);
//
//                                if (hfmt == null) {
//                                    Toast.makeText(getContext(), "当前业务资源文件尚未配置，请联系管理员", Toast.LENGTH_SHORT).show();
//                                    return;
//                                }
//                            }
//
//                        }
                    }
                    mAbFragmentManager.startActivity(stubObject, inTransition, outTransition);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {
        this.message = message;
        try {
            String json = new String(message.getBody(), "UTF-8");
            mJSONObject = new org.json.JSONObject(json);
            if (mJSONObject.has("status")) {
                String statusStr = mJSONObject.getString("status");
                if (statusStr.equals("error")) {
                    if (mJSONObject.has("state")) {
//                        tvState.setText(mJSONObject.getString("state"));
                    }
                    ivStateRed.setVisibility(VISIBLE);
                    ivStateBlue.setVisibility(GONE);
//                    tvState.setTextColor(getResources().getColor(R.color.gxtask_state_red));
                } else {
                    if (mJSONObject.has("state")) {
//                        tvState.setText(mJSONObject.getString("state"));
                    }
                    ivStateRed.setVisibility(GONE);
                    ivStateBlue.setVisibility(VISIBLE);
//                    tvState.setTextColor(getResources().getColor(R.color.gxtask_state_blue));
                }
            }
            if (mJSONObject.has("title")) {
                tvTitle.setText(mJSONObject.getString("title"));
            }
            if (mJSONObject.has("subtitle")) {
                tvSubTitle.setText(mJSONObject.getString("subtitle"));

            }
            try {
                if (!mJSONObject.optString("subtitleColor").equals("")) {
                    tvSubTitle.setTextColor(Color.parseColor(mJSONObject.optString("subtitleColor")));
                }
                if (!mJSONObject.optString("bottomBgColor").equals("")) {
                    rlBottom.setBackgroundColor(Color.parseColor(mJSONObject.optString("bottomBgColor")));
                }
                if (!mJSONObject.optString("titleBgColor").equals("")) {
                    llTitle.setBackgroundColor(Color.parseColor(mJSONObject.optString("titleBgColor")));

                    GradientDrawable myGrad = (GradientDrawable)llMessage.getBackground();
                    myGrad.setColor(Color.parseColor(mJSONObject.optString("titleBgColor")));
                }

                if (!mJSONObject.optString("contentBgColor").equals("")) {
                    llContent.setBackgroundColor(Color.parseColor(mJSONObject.optString("contentBgColor")));
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            if (mJSONObject.has("time")) {
                tvTime.setText(mJSONObject.getString("time"));
            }

            llContent.removeAllViews();
            JSONArray contentJsonArray = JSONArray.fromObject(mJSONObject.optString("viewColumn"));
            if (contentJsonArray != null && contentJsonArray.size() > 0) {
                for (int i = 0; i < contentJsonArray.size(); i++) {
                    JSONObject jsonObject = contentJsonArray.getJSONObject(i);
                    org.json.JSONObject taskData = mJSONObject.optJSONObject("TaskData");
                    if (taskData == null) {
                        return;
                    }
                    String type = jsonObject.optString("type");
                    String id = jsonObject.optString("id");
                    String value = "";
                    View view = View.inflate(getContext(), R.layout.chat_item_gxtask_content_item, null);
                    TextView tvName = (TextView) view.findViewById(R.id.tv_content_item_name);
                    TextView tvVale = (TextView) view.findViewById(R.id.tv_content_item_value);

                    if (type.equals("string")) {
                        value = taskData.optString(id);
                    }
                    if (type.equals("datetime") && !taskData.optString(id).equals("")) {
                        String time = taskData.optString(id);
                       String timeString  = new BigDecimal(time).toPlainString();
//                        time = time.substring(0, time.length() - 3);

                        value = DateUtils.timeStamp2Date(timeString, null);
                    }
                    try {
                        if (!jsonObject.optString("color").equals("")) {
                            tvVale.setTextColor(Color.parseColor(jsonObject.optString("color")));
                        }
                    } catch (IllegalArgumentException e) {

                    }
                    tvName.setText(jsonObject.optString("name"));
                    tvVale.setText(value);
                    llContent.addView(view);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {

    }

    @Override
    public void prepareForReuse() {

    }
}
